<template>
  <el-dialog
    title=""
    :visible.sync="showSelect"
    custom-class="otdr-port-select"
    width="fit-content"
    :show-close="false"
  >
    <div class="flex-column segment-list-box page-cutover table-content">
      <el-select
        v-if="operateType === 'add'"
        v-model="LinkSegemntId"
        class="mb-10"
        filterable
        clearable
        :placeholder="$t('PLEASE_SELECT_LINK')"
        @change="routeChange"
      >
        <el-option
          v-for="item in allRoutes"
          :key="item.segmentId"
          :value="item.segmentId"
          :label="item.segmentName"
        />
      </el-select>
      <div class="flex mb-10 align-center">
        <div class="port-status-list mr-10 idel-btn">
          {{ $t('IDLE') }}
        </div>
        <div
          v-for="i in portStatusList"
          :key="i.value"
          class="port-status-list mr-10"
          :class="'color-' + i.value.toLowerCase()"
        >
          {{ i.label }}
        </div>
        <el-popover width="350" trigger="hover">
          <div
            v-if="pageName !== 'routine'"
            class="text-color"
            v-html="$t('OTDR_PORT_STATUS_TIPS')"
          />
          <div v-else class="text-color" v-html="$t('OTDR_ROUTINE_TIPS')" />
          <i slot="reference" class="iconfont icon-AFSwenhao text-color" />
        </el-popover>
      </div>
      <el-table
        v-if="!!segmentList"
        ref="tableBox"
        border
        :data="segmentList"
        height="100%"
        :cell-class-name="cellClass"
        :cell-style="cellStyle"
      >
        <template slot="empty">
          <NullData />
        </template>
        <el-table-column
          type="index"
          :label="$t('SEQUENCE')"
          fixed="left"
          :width="resetSize(60)"
          align="center"
        />
        <div v-for="(item, index) in tableHead" :key="index">
          <el-table-column
            :label="item.segmentName"
            align="center"
            min-width="300"
            :render-header="tableRenderHeader"
            :prop="`segmentList${index}.startPort.bizName`"
            show-overflow-tooltip
          >
            <!-- A端端口 -->
            <el-table-column
              :label="item.startNode.nodeName"
              align="center"
              width="150"
              :prop="`segmentList${index}.startPort.bizName`"
              show-overflow-tooltip
            >
              <!-- 表头显示 -->
              <template #header>
                <div class="port-item fl">
                  <span>
                    {{ item.startNode.nodeName }}
                  </span>
                  <el-checkbox
                    v-if="
                      checkConnPort(item, 'startPort') &&
                        segmentList.length &&
                        afsPassStatus.includes(item.startNode.afsStatus)
                    "
                    v-model="startPortAllChecked"
                    :disabled="operateType === 'view' || endPortAllChecked"
                    style="margin-right: 1px"
                    @change="nodeClick(item.startNode, index, 'startPort')"
                  />
                </div>
              </template>
              <template slot-scope="scope">
                <div class="port-item fl">
                  <span>
                    {{ scope.row[`segmentList${index}`].startPort.bizName }}
                  </span>
                  <el-checkbox
                    v-if="scope.row[`segmentList${index}`].startPortCategory === 'VARIABLE_POINT'"
                    v-model="scope.row[`segmentList${index}`].startPort.checked"
                    :disabled="
                      scope.row[`segmentList${index}`].startPort.disabled ||
                        getConnDisabled(scope.row, 'endPort', index) ||
                        !afsInfo[scope.row[`segmentList${index}`].startPort.deviceId]
                    "
                    @change="
                      pointClick(
                        scope.row[`segmentList${index}`].startPort,
                        index,
                        item.startNode,
                        'startPort'
                      )
                    "
                  />
                  <i
                    v-if="scope.row[`segmentList${index}`].startPort.checked"
                    class="iconfont icon-AFSss-lux right-light"
                  />
                </div>
              </template>
            </el-table-column>
            <!-- 纤芯 -->
            <el-table-column
              v-if="item.cable"
              :label="item.cable.cableName"
              :prop="`segmentList${index}.fiber.fiberName`"
              :render-header="tableRenderHeader"
              align="center"
              width="150"
              show-overflow-tooltip
            />
            <!-- Z端端口 -->
            <el-table-column
              :label="item.endNode.nodeName"
              align="center"
              width="150"
              :prop="`segmentList${index}.endPort.bizName`"
              show-overflow-tooltip
            >
              <template #header>
                <div class="port-item fr">
                  <el-checkbox
                    v-if="
                      checkConnPort(item, 'endPort') &&
                        segmentList.length &&
                        afsPassStatus.includes(item.endNode.afsStatus)
                    "
                    v-model="endPortAllChecked"
                    style="margin-right: 5px"
                    :disabled="operateType === 'view' || startPortAllChecked"
                    @change="nodeClick(item.endNode, index, 'endPort')"
                  />
                  <span>
                    {{ item.endNode.nodeName }}
                  </span>
                </div>
              </template>
              <template slot-scope="scope">
                <div class="port-item fr">
                  <el-checkbox
                    v-if="scope.row[`segmentList${index}`].endPortCategory === 'VARIABLE_POINT'"
                    v-model="scope.row[`segmentList${index}`].endPort.checked"
                    :disabled="
                      scope.row[`segmentList${index}`].endPort.disabled ||
                        getConnDisabled(scope.row, 'startPort', index) ||
                        !afsInfo[scope.row[`segmentList${index}`].endPort.deviceId]
                    "
                    @change="
                      pointClick(
                        scope.row[`segmentList${index}`].endPort,
                        index,
                        item.endNode,
                        'endPort'
                      )
                    "
                  />
                  <span>
                    {{ scope.row[`segmentList${index}`].endPort.bizName }}
                  </span>
                  <i
                    v-if="scope.row[`segmentList${index}`].endPort.checked"
                    class="iconfont icon-AFSss-lux left-light"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </div>
      </el-table>
      <div v-else class="no-data">{{ $t('ENTER_LINK_DATA') }}</div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="goBack">{{ $t('CANCEL') }}</el-button>
      <el-button v-if="!!segmentList" type="primary" @click="next">
        {{ $t('NEXT') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { correctOrder, tableRenderHeader } from '@/utils/common'
  import LogicSegmentApi from '@/api/oen/LogicSegmentApi'
  import logicSegmentApi from '@/api/oen/LogicSegmentApi'
  import otdrTest from '@/api/afs/OtdrTest'

  export default {
    props: {
      showSelect: {
        type: Boolean,
        default: false
      },
      formData: {
        type: Object,
        default: () => {
          return {
            bizType: 'LINK_DETECT',
            processName: '',
            cut: false,
            portList: [],
            otdrParam: {}
          }
        }
      },
      operateType: { type: String, default: 'add' },
      pageName: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        allRoutes: [],
        LinkSegemntId: '',
        segmentList: null,
        afsList: [],
        afsPassStatus: [
          'TRANSFER',
          'OTDR_TRANSFER',
          'OTDR_TEST',
          'OTDR_RESTORE',
          'MOTION',
          'UNPLUG',
          'IDLE',
          'LOWER_POWER',
          'STANDBY',
          'LOW_POWER',
          'READY',
          'CANCEL',
          'DISABLE'
        ],
        routeData: {
          startNode: {},
          endNode: {},
          networkSegmentList: [],
          tableHead: []
        },
        afsInfo: {},
        startPortAllChecked: false,
        endPortAllChecked: false
      }
    },
    computed: {
      ...mapGetters(['dictList']),
      tableHead() {
        console.log('this.routeData.tableHead', this.routeData.tableHead)
        return this.routeData.tableHead
      },
      portStatusList() {
        return this.dictList.PORT_STATUS
          ? this.dictList.PORT_STATUS.filter(
            i => i.value !== 'IDLE' && i.value !== 'LOCK' && i.value !== 'CONN'
          )
          : []
      }
    },
    methods: {
      tableRenderHeader(h, data) {
        return tableRenderHeader(h, data)
      },
      loadData(searchData = {}) {
        this.LinkSegemntId = ''
        this.resetData()
        // 获取路由列表
        logicSegmentApi
          .queryPage({ ...searchData, filtrationBiz: true }, { page: 1, size: 10000 })
          .then(res => {
            console.log('res', res)
            this.allRoutes = res.list || []
          })
      },
      // 重置路由、选中端口、表单数据
      resetData() {
        this.startPortAllChecked = false
        this.endPortAllChecked = false
        this.segmentList = null
        this.routeData = { ...this.$options.data().routeData }
      },
      // 当前路由选择改变
      async routeChange(linkSegmentId) {
        this.LinkSegemntId = linkSegmentId || this.LinkSegemntId
        this.resetData()
        if (!this.LinkSegemntId) return
        let curData = this.allRoutes.find(i => i.segmentId === this.LinkSegemntId)
        if (!curData && this.formData.planId) {
          const res = await logicSegmentApi.queryPage(
            {
              keyword: this.LinkSegemntId,
              reach: '',
              filtrationBiz: false
            },
            { page: 1, size: 1 }
          )
          curData = res.list[0]
          this.allRoutes.push(curData)
        }
        if (!curData) {
          this.$message.error(this.$t('NO_LINK_SEGMENT_FOUND'))
          return
        }
        this.routeData = { ...curData }
        this.getAfsList()
        this.formData.startNodeId = this.routeData.startNodeId
        this.formData.endNodeId = this.routeData.endNodeId
        this.formData.segmentId = linkSegmentId
        this.formData.segmentName = this.routeData.segmentName // 记录到操作日志
        this.getSegmentList()
      },
      // 获取afs列表用于判断首尾afs是否可打光测试
      getAfsList() {
        this.routeData.networkSegmentList = correctOrder(
          this.routeData.networkSegmentList,
          this.routeData.startNodeId
        )
        this.routeData.tableHead = this.routeData.networkSegmentList
        this.afsList = []
        this.routeData.networkSegmentList.forEach((i, index) => {
          i.startNode.checked = false
          i.endNode.checked = false
          if (index === 0 && i.startNodeCategory === 'AFS') {
            this.afsList.push(i.startNodeId)
          }
          if (i.endNodeCategory === 'AFS') {
            this.afsList.push(i.endNodeId)
          }
        })
        // console.log('this.tableHead', this.tableHead)
      },
      // 获取路由通道列表
      getSegmentList(data) {
        LogicSegmentApi.detail({
          segmentId: this.routeData.segmentId
        }).then(res => {
          res = res || []
          const deviceId = []
          res.forEach(i => {
            i.segmentList.forEach((j, index) => {
              // 例行测试查看、修改数据重组
              if (this.operateType !== 'add') {
                j.startPort.checked = this.formData.stepList.some(z =>
                  z.portList.includes(j.startPort.portId)
                )
                j.endPort.checked = this.formData.stepList.some(z =>
                  z.portList.includes(j.endPort.portId)
                )
              } else {
                j.startPort.checked = false
                j.endPort.checked = false
              }
              deviceId.push(j.startPort.deviceId)
              deviceId.push(j.endPort.deviceId)
              j.startPort.bizName = this.$utils.handleServiceI18n(j.startPort.bizName)
              j.endPort.bizName = this.$utils.handleServiceI18n(j.endPort.bizName)
              j.index = index
              /**
               * 端口disabled状态根据:
               * 1.端口状态：空闲、成端、备用、损坏
               * 2.设备状态：afsPassStatus
               * 3.同通道端口选中：不能对向打光
               */
              // console.log(this.tableHead[index].startNode.afsStatus)
              j.startPort.disabled =
                this.disabledPort(j, 'startPort') ||
                !this.afsPassStatus.includes(this.tableHead[index].startNode.afsStatus)
              j.endPort.disabled =
                this.disabledPort(j, 'endPort') ||
                !this.afsPassStatus.includes(this.tableHead[index].endNode.afsStatus)
              i['segmentList' + index] = j
            })
          })
          this.getAfsInfo(deviceId)
          res.sort((a, b) => {
            return a.segmentList0.startPort.bizName.localeCompare(
              b.segmentList0.startPort.bizName,
              'zh-Hans-CN',
              { sensitivity: 'accent', numeric: true }
            )
          })
          this.segmentList = res
        })
      },
      getAfsInfo(deviceId) {
        this.afsInfo = {}
        if (deviceId.length === 0) return
        otdrTest.deviceOtdrInstallInfo({ deviceIds: Array.from(new Set(deviceId)) }).then(res => {
          this.afsInfo = res || {}
        })
      },
      // 端口全选变化
      nodeClick(nodeData, index, portType) {
        const checkedVal = this[portType + 'AllChecked']
        nodeData.checked = checkedVal

        // 不能能对向打光
        this.segmentList.forEach(i => {
          i[`segmentList${index}`][portType].checked = false
          if (
            !i[`segmentList${index}`][portType].disabled &&
            !this.getConnDisabled(i, portType === 'startPort' ? 'endPort' : 'startPort', index) &&
            this.afsInfo[i[`segmentList${index}`][portType].deviceId]
          ) {
            i[`segmentList${index}`][portType].checked = checkedVal
          }
        })
        this.$nextTick(() => {
          this.$refs.tableBox.doLayout()
        })
      },
      // 通过选中端口设置不能对向打光的端口disable
      getConnDisabled(row, type, index) {
        // A向打光的端口前面的端口不能选择Z向
        if (type === 'startPort') {
          return row.segmentList.some((i, iIndex) => i[type].checked && iIndex <= index)
        } else {
          // Z向打光的端口后续端口不能选择A向
          return row.segmentList.some((i, iIndex) => i[type].checked && iIndex >= index)
        }
      },
      // 端口点击事件,关联全选和不全选
      pointClick(data, index, nodeData, portType) {
        if (!data.checked) {
          this.segmentList[index].checked = false
        } else {
          this.segmentList[index].checked = !this.segmentList.some(
            i =>
              !i[`segmentList${index}`][portType].disabled &&
              !i[`segmentList${index}`][portType].checked
          )
        }
      },
      //   下一步
      next() {
        this.formData.portList = []
        // 遍历获取已选中的端口
        this.segmentList.forEach(i => {
          const networkLinkChannelBoList = i.segmentList.map((z, index) => {
            return {
              networkSegment: this.routeData.networkSegmentList[index],
              segmentChannel: z
            }
          })
          i.segmentList.forEach((j, index) => {
            j.startPort.checked &&
              this.formData.portList.push({
                deviceId: j.startNodeId,
                deviceName: this.tableHead[index].startNode.nodeName,
                testDirection: 'Z',
                portId: j.startPort.portId,
                networkLinkChannelBoList: networkLinkChannelBoList
              })
            j.endPort.checked &&
              this.formData.portList.push({
                deviceId: j.endNodeId,
                deviceName: this.tableHead[index].endNode.nodeName,
                testDirection: 'A',
                portId: j.endPort.portId,
                networkLinkChannelBoList: networkLinkChannelBoList
              })
          })
        })
        this.formData.segmentId = this.formData.segmentId || this.routeData.segmentId
        if (this.formData.portList.length === 0) {
          this.$message.error(this.$t('PLEASE_SELECT') + this.$t('PORT'))
          return
        } else {
          // if (this.pageName === 'routine' && this.formData.portList.length > 100) {
          //   this.$message.error(this.$t('ROUTINE_MAX_NUMBER'))
          //   return
          // }
          // 校验选中端口的设备是否支持otdr测试
          this.$emit(
            'next',
            // 例行测试需要物理网段
            this.routeData.networkSegmentList.map(i => i.segmentId)
          )
        }
      },
      // 根据节点状态跟网格颜色
      cellClass({ row, column }) {
        if (column.property) {
          const keys = column.property.split('.')
          return 'color-' + (row[keys[0]][keys[1]].status || '').toLowerCase()
        }
      },
      // 根据节点状态跟网格颜色
      cellStyle({ row, rowIndex, column, columnIndex }) {
        const borderValue = '2px dashed green'
        const borderData = {
          borderTop: '',
          borderRight: '',
          borderBottom: '',
          borderLeft: ''
        }
        if (
          column.property &&
          column.property.indexOf('endPort') !== -1 &&
          columnIndex !== this.$refs.tableBox.columns.length - 1
        ) {
          borderData.borderLeft = borderValue
          if (rowIndex === this.segmentList.length - 1) {
            borderData.borderBottom = borderValue
          }
          if (rowIndex === 0) {
            borderData.borderTop = borderValue
          }
        }
        if (column.property && column.property.indexOf('startPort') !== -1 && columnIndex !== 1) {
          borderData.borderRight = borderValue
          if (rowIndex === this.segmentList.length - 1) {
            borderData.borderBottom = borderValue
          }
          if (rowIndex === 0) {
            borderData.borderTop = borderValue
          }
        }
        return borderData
      },
      // 端口连接的对端是否是可测试的端口（除光分和传输都可测试）
      checkConnPort(data, side) {
        const nodeIndex = this.afsList.findIndex(
          i => i === data[side === 'startPort' ? 'startNodeId' : 'endNodeId']
        )
        let canTest = true
        // 非AFS的端口不能选
        if (nodeIndex === -1) {
          canTest = false
        }
        const firstDevice = this.tableHead[0]
        const lastDevice = this.tableHead[this.tableHead.length - 1]
        // 第一个afs判断路由第一个设备是否是传输
        if (
          nodeIndex === 0 &&
          side === 'endPort' &&
          (firstDevice.startNodeCategory === 'TRANSPORT' ||
            firstDevice.startNodeCategory === 'LIGHT_SPLIT')
        ) {
          canTest = false
        }
        // 最后一个afs判断路由最后一个设备是否是传输
        if (
          nodeIndex === this.afsList.length - 1 &&
          side === 'startPort' &&
          (lastDevice.endNodeCategory === 'TRANSPORT' ||
            lastDevice.endNodeCategory === 'LIGHT_SPLIT')
        ) {
          canTest = false
        }

        if (firstDevice.startNodeId === lastDevice.endNodeId) {
          canTest = false
        }
        return canTest
      },
      // 设置端口不可选择状态（查看、例测下端口没有曲线的、不可割接状态的）
      disabledPort(data, side) {
        const canTest = this.checkConnPort(data, side)
        return (
          this.operateType === 'view' ||
          !canTest ||
          (this.pageName === 'routine' && !data[side].isRefCurve) ||
          !this.showPort(data[side])
        )
      },
      // 是否可割接节点判断(能进行割接和检测的状态：空闲、成端、备用、损坏、进行中)
      showPort(data) {
        return (
          data.portCategory === 'VARIABLE_POINT' &&
          (data.status === 'IDLE' ||
            data.status === 'CONN' ||
            data.status === 'BACKUP' ||
            data.status === 'DAMAGE' ||
            (this.pageName === 'routine' && data.status === 'PROCESS'))
        )
      },
      goBack() {
        this.LinkSegemntId = ''
        this.resetData()
        this.$emit('goBack')
      }
    }
  }
</script>

<style scoped lang="scss">
  @import 'src/assets/css/mixin.module';
  .table-content {
    min-width: 350px;
    width: fit-content;
    max-height: calc(70vh - 205px);
  }
  .el-dialog__wrapper :deep(.otdr-port-select .el-dialog__header) {
    padding: 10px;
  }

  .port-status-list.idel-btn {
    @include themeify {
      color: themed('textColor');
      border: 1px solid themed('textColor');
    }
  }
  .no-data {
    width: 100%;
    height: 100%;
    line-height: 60px;
    color: #909399;
    font-size: 12px;
    text-align: center;
    border: 1px solid #ebeef5;
    @include themeify {
      color: lighten(themed('textColor'), 10%);
      border: 1px solid themed('tableBorderColor');
    }
  }

  .right-light {
    position: absolute;
    right: 5px;
    transform: rotate(-135deg);
    @include themeify {
      color: lighten(themed('textColor'), 10%);
    }
  }
  .left-light {
    position: absolute;
    left: 5px;
    transform: rotate(45deg);
    @include themeify {
      color: lighten(themed('textColor'), 10%);
    }
  }
</style>
